#!/bin/bash
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# use ./build.sh -nosym to build content_shell without symbol.
set -e
basedir=$(dirname "$0")
CUR_DIR=$PWD
ROOT_DIR="${CUR_DIR%/src*}""/src"
# Global variables.
BUILD_TARGET_CONTENT_SHELL="content_shell_web"
BUILD_TARGET_CHROME="chrome_main_web"
BUILD_TARGET_ELECTRON="electron"
TEXT_BOLD="\033[1m"
TEXT_NORMAL="\033[0m"

#Add build args begin
buildargs="
is_electron_build = true
# root_extra_deps = [ \"//electron\" ]

# Registry of NMVs --> https://github.com/nodejs/node/blob/main/doc/abi_version_registry.json
node_module_version = 132

v8_promise_internal_field_count = 1
v8_embedder_string = \"-electron.0\"

# TODO: this breaks mksnapshot
v8_enable_snapshot_native_code_counters = false

# we use this api
v8_enable_javascript_promise_hooks = true

enable_cdm_host_verification = false
proprietary_codecs = true

enable_printing = true

# Removes DLLs from the build, which are only meant to be used for Chromium development.
# See https://github.com/electron/electron/pull/17985
angle_enable_vulkan_validation_layers = false
dawn_enable_vulkan_validation_layers = false

# These are disabled because they cause the zip manifest to differ between
# testing and release builds.
# See https://chromium-review.googlesource.com/c/chromium/src/+/2774898.
enable_pseudolocales = false

# Make application name configurable at runtime for cookie crypto
allow_runtime_configurable_key_storage = true

# CET shadow stack is incompatible with v8, until v8 is CET compliant
# enabling this flag causes main process crashes where CET is enabled
# Ref: https://source.chromium.org/chromium/chromium/src/+/45fba672185aae233e75d6ddc81ea1e0b30db050:v8/BUILD.gn;l=357
enable_cet_shadow_stack = false

# For similar reasons, disable CFI, which is not well supported in V8.
# Chromium doesn't have any problems with this because they do not run
# V8 in the browser process.
# Ref: https://source.chromium.org/chromium/chromium/src/+/45fba672185aae233e75d6ddc81ea1e0b30db050:v8/BUILD.gn;l=281
is_cfi = false

# TODO: fix this once sysroots have been updated.
use_qt = false

# https://chromium-review.googlesource.com/c/chromium/src/+/4365718
# TODO(codebytere): fix perfetto incompatibility with Node.js.
use_perfetto_client_library = false

# Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4402277
enable_check_raw_ptr_fields = false



# This may be guarded behind is_chrome_branded alongside
# proprietary_codecs https://webrtc-review.googlesource.com/c/src/+/36321,
# explicitly override here to build OpenH264 encoder/FFmpeg decoder.
# The initialization of the decoder depends on whether ffmpeg has
# been built with H.264 support.
rtc_use_h264 = proprietary_codecs

# By default, Electron builds ffmpeg with proprietary codecs enabled. In order
# to facilitate users who don't want to ship proprietary codecs in ffmpeg, or
# who have an LGPL requirement to ship ffmpeg as a dynamically linked library,
# we build ffmpeg as a shared library.
is_component_ffmpeg = true

chrome_pgo_phase = 0



  target_os=\"ohos\"
  is_component_build=false
  is_chrome_branded=false
  use_official_google_api_keys=false
  use_ozone=true
  use_aura=true
  use_v8_context_snapshot=true
  ozone_auto_platforms=false
  ozone_platform=\"ohos\"
  ozone_platform_ohos=true
  enable_extensions=true
  ffmpeg_branding=\"Chrome\"
  use_kerberos=false
  use_bundled_fontconfig=true
  enable_resource_allowlist_generation=false
  clang_use_chrome_plugins=false
  enable_message_center=true
  use_custom_libcxx=false
  use_sysroot=true
  gpu_switch=\"on\"
  proprietary_codecs=true
  media_use_ffmpeg=true
  media_use_openh264=true
  angle_enable_vulkan_system_info=true
  v8_enable_builtins_optimization=false
  content_enable_legacy_ipc = true
  enable_rust=true
  enable_rust_cxx=true
  enable_chromium_prelude=true
  clang_base_path=\"//ohos_sdk/openharmony/native/llvm\"
  llvm_ohos_mainline=true
  rustc_version=\"bca5fdebe0e539d123f33df5f2149d5976392e76-1-llvmorg-20-init-9764-gb81d8e90\"
  rust_sysroot_absolute=\"//ohos_sdk/rust-toolchain\"
  enable_ppapi=true
  override_electron_version=\"34.0.2\"
"
#Add build args end

#build args: build mode
is_debug=false
is_official_build=true
#build args: build mode end

buildgn=1
buildcount=0
buildccache=0
buildsymbol=0
buildproduct=""
buildarg_cpu="target_cpu=\"arm64\""
buildarg_musl="use_musl=true"
build_dir="out/musl_64/"
build_product_name="product_name=\"all\""
build_target="${BUILD_TARGET_ELECTRON}"
build_output=""
build_asan=0

usage() {
  echo -ne "USAGE: $0 [OPTIONS] [PRODUCT]

${TEXT_BOLD}OPTIONS${TEXT_NORMAL}:
  -j N              force number of build jobs
  -ccache           Enable CCache.
  -t <target>       Build target, for example::
                      ./build.sh
                      ./build.sh -t \"base:base\"
                      ./build.sh -t \"content/test:content_unittests\"
  -o <output_dir>   Output directory, for example: Default.
  -d                Build with Debug mode.

"
}

while [ "$1" != "" ]; do
  case $1 in
    "-j")
      shift
      buildcount=$1
    ;;
    "-ccache")
      buildccache=1
    ;;
    "-sym")
      buildsymbol=1
    ;;
    "-t")
      shift
      build_target=$1
      ;;
    "-o")
      shift
      build_output=$1
      ;;
    "-d")
      is_debug=true
      is_official_build=false
      echo "build mode: Debug"
      ;;
    "-h")
      usage
      exit 0
      ;;
    *)
      echo " -> $1 <- is not a valid option, please follow the usage below: "
      usage
      exit 1
    ;;
  esac
  shift
done

buildargs="${buildargs} is_debug=${is_debug} is_official_build=${is_official_build} "

if [ "-${build_output}" != "-" ]; then
  build_dir="out/${build_output}/"
fi

case "${build_target}" in
  "c"|"${BUILD_TARGET_CONTENT_SHELL}")
    build_target="${BUILD_TARGET_CONTENT_SHELL}"
    buildargs="${buildargs}safe_browsing_mode=0
    ohos_build_target=\"content_shell\"
    "
    ;;
  "b"|"${BUILD_TARGET_CHROME}")
    build_target="${BUILD_TARGET_CHROME}"
    buildargs="${buildargs}safe_browsing_mode=1
    ohos_build_target=\"chromium\"
    "
    ;;
  "e"|"${BUILD_TARGET_ELECTRON}")
    build_target="${BUILD_TARGET_ELECTRON}"
    buildargs="${buildargs}safe_browsing_mode=1
    ohos_build_target=\"electron\"
    "
    ;;
  *)
    echo "build_target: ${build_target}"
    ;;
esac

SYMBOL_LEVEL=1
if [ $buildsymbol = 1 ]; then
  SYMBOL_LEVEL=2
fi

if [ $buildcount = 0 ]; then
  buildcount=$(grep processor /proc/cpuinfo | wc -l)
fi

if [ $buildccache = 1 ]; then
  if [ $buildcount = 0 ]; then
    buildcount=64
  fi
  GN_ARGS="cc_wrapper=\"ccache\" clang_use_chrome_plugins=false linux_use_bundled_binutils=false"
  export CCACHE_CPP2=yes
fi

if [ ${build_asan} -eq 1 ]; then
  GN_ARGS="${GN_ARGS} is_asan=true"
else
  GN_ARGS="${GN_ARGS} is_asan=false"
fi

# Extract ohos-sdk.
if [ -f "src/ohos_sdk/.install" ]; then
  bash "src/ohos_sdk/.install"
  if [ $? -ne 0 ]; then
    echo "ERROR: Failed to install ohos-sdk, abort!"
    exit 1
  fi
fi

cd src

time_start_for_build=$(date +%s)
time_start_for_gn=$time_start_for_build

if [ $buildgn = 1 ]; then
  echo "generating args list: $buildargs $GN_ARGS"
  third_party/depot_tools/gn gen $build_dir --export-compile-commands --args="$buildargs $buildarg_cpu $buildarg_musl $build_product_name $GN_ARGS symbol_level=$SYMBOL_LEVEL"
fi
time_end_for_gn=$(date +%s)

third_party/depot_tools/ninja -C $build_dir -j$buildcount ${build_target}

time_end_for_build=$(date +%s)

time_format() {
  hours=$((($1 - $2) / 3600))
  minutes=$((($1 - $2) % 3600 / 60))
  seconds=$((($1 - $2) % 60))
}

time_format $time_end_for_gn $time_start_for_gn
printf "\n\e[32mTime for gn  : %dH:%dM:%dS \e[0m\n" $hours $minutes $seconds
time_format $time_end_for_build $time_end_for_gn
printf "\e[32mTime for build : %dH:%dM:%dS \e[0m\n" $hours $minutes $seconds
time_format $time_end_for_build $time_start_for_build
printf "\e[32mTime for Total : %dH:%dM:%dS \e[0m\n\n" $hours $minutes $seconds

echo "build done"
